<template>
	<div style="padding:0 37px 0 44px">	
		<div class="breadcrumb-father">
			<div class="new-breadcrumb" style="max-width:300px;">
				
				<router-link  :to="{path:'/welcome'}">
					<img src="../../assets/imgs/Home.png" alt="">
				</router-link>
				<!-- <a href="javascript:void(0)">
				</a> -->
				<span>{{$t('newcash.Withdrawal')}}</span>
				<span class="arrow">></span>
				<!-- <a href="javascript:void(0)">
				</a> -->
				<span>{{$t('newcash.pendingWithdrawalApproval')}}</span>
			</div>
		</div>

		<div class="card-table">
			<div class="card-table-title">
				<svg aria-hidden="true" class="svg-icon svg-title-icon">
					<use xlink:href="#icon-shanghutixian"></use>
				</svg>
				<span>{{$t('newcash.pendingWithdrawalApproval')}}</span>
			</div>
			<!--提现列表-->
			<el-table border :key='tableKey' :data='withdrawCashDatas' height=500 @cell-mouse-enter="showHandle" @cell-mouse-leave="hiddenHandle" v-loading="loading" :element-loading-text="$t('button.loading')" element-loading-background="rgba(255, 255, 255, 1)">
				<el-table-column :label="$t('index.Number')" fixed="left" width="80" type='index'> </el-table-column>
				<el-table-column width="200px" :label="$t('newcash.requestDate')" prop="startTime">
	  			</el-table-column>
				<el-table-column width="220px" :label="$t('newcash.agentOrMerchantName')" prop="mername" class-name="title_name" :formatter="judgeMerName">
	  			</el-table-column>
				<el-table-column width="100px" :label="$t('newcash.bankName')" prop="bankname">
				</el-table-column>
				<el-table-column width="150px" :label="$t('newcash.bankAccount')" prop="bankCard">
				</el-table-column>
				<el-table-column width="180px" :label="$t('newcash.accountName')" prop="drawname">
				</el-table-column>
				<el-table-column width="220px" :label="$t('newcash.withdrawAmount')" prop="withdrawal_amount" :formatter='judgeMoney'>
				</el-table-column>
				<el-table-column width="200px" :label="$t('newcash.withdrawType')" prop="type" :formatter='judgeType'>
				</el-table-column>
				<!-- <el-table-column width="180px" :label="$t('newcash.withdrawFee')" prop="poundage" :formatter="judgePoundage">
				</el-table-column> -->
				<!-- <el-table-column width="180px" :label="$t('newcash.remitAmount')" prop="amount" :formatter="judgeAmount">
				</el-table-column> -->
				<el-table-column width="180px" :label="$t('cash.auditStatus')" prop="state" :formatter='judge'>
				</el-table-column>
				<!-- <el-table-column width="150px" :label="$t('cash.auditTime')" prop="inspectTime">
				</el-table-column>
				<el-table-column width="150px" :label="$t('cash.remittanceDate')" prop="remitTime">
				</el-table-column> -->
				<el-table-column fixed="right" class-name="animate_td handle-hidden-3">
					<template slot-scope="scope">
						<a class="svg-link-class" :title="$t('cash.adopt')" v-if =" userType === '9' && scope.row.state==='0'" @click="handerCheckCashPass(scope.row.id,scope.row.type,scope.row.state,scope.row.mername,scope.row.distributorName)">
							<svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-tonguo"></use></svg>
						</a>
						<a class="svg-link-class" :title="$t('newcash.reject')" v-if =" userType === '9' && scope.row.state==='0'" @click="handerCheckCashReject(scope.row.id,scope.row.type,scope.row.state,scope.row.mername,scope.row.distributorName)">
							<svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-bohui"></use></svg>
						</a>
						<a class="svg-link-class" :title="$t('newcash.paid')" v-if =" userType === '11' && scope.row.state==='1'" @click="handerCheckCashPay(scope.row.id,scope.row.state,scope.row.mername)">
							<svg aria-hidden="true" class="svg-icon svg-action-icon"><use xlink:href="#icon-dakuan"></use></svg>
						</a>						
					</template>
				</el-table-column>
			</el-table>
		</div>
  		
  		<div class="pagination-container">
    		<el-pagination :total="res.total" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="searchCashData.page" :page-sizes="[15,20,30, 50]" :page-size="searchCashData.pageSize" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
  		</div>
	</div>
</template>

<script>
	import { withdrawCashAll,checkCash,withdrawCashPay,findNotCashRecord } from 'api/merchantWithdrawCash/index';
	import { Message , MessageBox} from 'element-ui';
	export default {
		name: 'WithdrawalCash',
		data(){
			return {
				tableKey: 0,
				userType:localStorage.getItem('userType'),
			    res:[],
				withdrawCashDatas:[],
				//按条件搜索订单所需参数
				searchCashData:{
					page:1,
					pageSize:15
				},
				list: null,
//			    total: null,//查询得知总订单数
			    //第一次进提现
			    oneCashData:{
			    	page:1,
					pageSize:15
				},
				rorateFlag:true,
				last_td_arr:[],
				currency:undefined,
				oldPage: null,
                loading: true,
                companyId:localStorage.getItem('companyId'),
			}
		},
		watch:{
		  'searchCashData.page':function(newVal,oldVal){
		      this.oldPage = oldVal;
		  },
		},
		created () {
			this.getWithdrawCashList(this.oneCashData);

			if (this.companyId == '1') this.currency = 'HK$ ';
            if (this.companyId == '2') this.currency = 'A$ ';
		},
		methods: { 
			showHandle(row, column, cell, event){
				// console.log(row);
				for(let i = 0;i<this.withdrawCashDatas.length;i++){
					if(this.withdrawCashDatas[i].id === row.id){
						this.tableIndex = i;
						const table_row = $(".el-table__fixed-right").find('.el-table__row')[i];
						$(table_row).find('td:last').removeClass('handle-hidden-'+ this.last_td_arr[i] );
						$(".el-table__fixed-right").addClass("fixed-column-" + this.last_td_arr[i] );
						$(".el-table__fixed-right").css("z-index","22");
						var action_div = $(table_row).find('td:last').children("div");
						$(action_div).stop().animate({"right": "0"});
					}
				}
				// 判断项目数目是否导致滚动条出现
				if(this.withdrawCashDatas.length <= 15){
					$(".el-table__fixed-right").addClass("right-zero");
				}else{
					$(".el-table__fixed-right").removeClass("right-zero");
				}
			},
			hiddenHandle(row, column, cell, event){
				const table_row = $(".el-table__fixed-right").find('.el-table__row')[this.tableIndex];
				$(".el-table__fixed-right").css("z-index","0");
				var action_div = $(table_row).find('td:last').children("div");
				$(action_div).stop().animate({"right": "-360px"});
			},
			judgeMerName(row) {
				return row.mername ? row.mername : row.distributorName;
			},
			// 格式化打款金额(V2.8丢弃)
			// judgeAmount(row){
			// 	if(row.hasOwnProperty('amount')){
			// 		let formatAmount = row.amount;
			// 		return formatAmount = this.currency + this.fmoney(formatAmount,2);
			// 	};
			// },
			// 格式化手续费
			judgePoundage(row){
				if(row.hasOwnProperty('poundage')){
					let formatPoundage = row.poundage;
					return formatPoundage = this.currency  + this.fmoney(formatPoundage,2);
				};
			},
			//格式化显示数据
			judge(data){
				let state = data.state
				if(state === '0'){
					return state = this.$t('newcash.pending')
				}
				if(state === '1'){
					return state = this.$t('newcash.approved')
				}
				if(state === '2'){
					return state = this.$t('newcash.rejected')
				}
				if(state === '3'){
					return state = this.$t('newcash.paid')
				}
			},
			//格式化提现金额
			judgeMoney(row){
				let formatMoney = row.withdrawal_amount;
				// return formatMoney;
				return formatMoney = this.currency + this.fmoney(formatMoney,2);
			},
			// 格式化金额
			fmoney(s, n){   
				if( s === "" || s === undefined ) return s = "0.00";
				s = s / 100;
				n = n > 0 && n <= 20 ? n : 2;   
				s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";   
				var l = s.split(".")[0].split("").reverse(),   
				r = s.split(".")[1];   
				let t = "";   
				for(let i = 0; i < l.length; i ++ )
				{   
					t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");   
				}   
				return t.split("").reverse().join("") + "." + r;
			},
			//格式化显示数据
			judgeType(data){
				return data.type == '0' ? this.$t('cash.check') : this.$t('cash.onlineBanking');
			},
			//封装了提现查询的方法
			getWithdrawCashList(data,str){
				
				const _that = this;

				_that.loading = true;

				if( str == 'CurrentChange' ){
				  // 获取所有分页项数，循环去除选中样式，对点击前的项数添加选中样式
				  let obj = $('.el-pager .number');
				  for( let i = 0; i < obj.length; i++){
				      if($(obj[i]).html() == this.oldPage) {
				        $(obj[i]).addClass('active');
				      } else {
				        $(obj[i]).removeClass('active');
				      }
				  }
				}

				this.last_td_arr = [];
				findNotCashRecord(data).then(res => {
					// console.log('提现查询返回的数据--------');
					this.res = res.value;
					// console.log(res.value);
					this.withdrawCashDatas = res.value.rows;

					// 如果是分页触发，循环去除选中样式，对点击后的项数添加选中样式
					if( str == 'CurrentChange' ){
					  let obj = $('.el-pager .number');
					  for( let i = 0; i < obj.length; i++){
					      if($(obj[i]).html() == this.searchCashData.page) {
					        $(obj[i]).addClass('active');
					      } else {
					        $(obj[i]).removeClass('active');
					      }
					  }
					}

					setTimeout(function (param) { 
						const td_last_child = $(".el-table__body-wrapper tr td:last-child");
						for(let i=0;i<td_last_child.length;i++){
						$(td_last_child[i]).removeClass('handle-hidden-3');
						}
						const td_fixed_last_child = $(".el-table__fixed-right tr td:last-child");
						for(let i=0;i<td_fixed_last_child.length;i++){
							// console.log($(td_fixed_last_child[i]).find('.svg-link-class').length);
							_that.last_td_arr.push($(td_fixed_last_child[i]).find('.svg-link-class').length);
							if( $(td_fixed_last_child[i]).find('.svg-link-class').length === 1 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-3').removeClass('handle-hidden-2').addClass('handle-hidden-1');
							} else if( $(td_fixed_last_child[i]).find('.svg-link-class').length === 2 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-3').removeClass('handle-hidden-1').addClass('handle-hidden-2');
							} else if( $(td_fixed_last_child[i]).find('.svg-link-class').length === 3 ){
								$(td_fixed_last_child[i]).removeClass('handle-hidden-1').removeClass('handle-hidden-2').addClass('handle-hidden-3');
							} 
						}

						const title_name_arr = $(".el-table__body-wrapper .title_name .cell");
						for(let j = 0;j<title_name_arr.length;j++){
							$(title_name_arr[j]).attr('title',$(title_name_arr[j]).html());
							// if(_that.getStrL($(title_name_arr[j]).html()) > 20 ){
							// }
						}
						
						_that.loading = false;

					},500)
				}).catch(error=>{
					console.log(error);
				})
			},
			// 判断字符串长度的方法
			getStrL(str){
				let l = str.length; 
				let blen = 0; 
				for(let i=0; i<l; i++) { 
					if ((str.charCodeAt(i) & 0xff00) != 0) { 
						blen ++; 
					} 
					blen ++; 
				}
				return blen;
			},
			//通过按钮方法
			handerCheckCashPass(id,type,state,name,dname){
				this.$msgbox({
					title: this.$t("hint.Alert"),
					message: this.$t('newcash.confirmToApprove') + (name?name:dname) + this.$t('newcash.withdrawRequestFrom'),
					showClose: false,
					closeOnClickModal:false,
					showCancelButton: true,
					confirmButtonText: this.$t("button.OK"),
					cancelButtonText: this.$t("button.Cancel"),
					beforeClose: (action, instance, done) => {
						if (action == "confirm") {
							if(state === '0'){
								checkCash(id,1).then(res=>{
									// console.log('通过按钮返回的信息');
									// console.log(res);
									if(res.code === 1){
										Message({
											message: this.$t('hint.OperationFail'),
											type: 'warning',
											duration: 3 * 1000	
										});	
									}else if(res.code === 0){
										this.getWithdrawCashList(this.searchCashData);
										Message({
											message: this.$t('hint.OperationSuccess'),
											type: 'success',
											duration: 3 * 1000	
										});	
									}
								})
							} 
							// else if(state === '1') {
							// 	Message({
							// 		message: this.$t('cash.auditHasPassed'),
							// 		duration: 3 * 1000	
							// 	});
							// }else if(state === '2'){
							// 	Message({
							// 		message: this.$t('cash.theAuditHasBeenRejected'),
							// 		type: 'error',
							// 		duration: 3 * 1000	
							// 	});
							// }else{
							// 	Message({
							// 		message: this.$t('cash.errOperation'),
							// 		type: 'error',
							// 		duration: 3 * 1000	
							// 	});
							// }
						}
						done();
					}
				}).catch(()=>{});
			},
			//驳回按钮方法
			handerCheckCashReject(id,type,state,name,dname){
				this.$msgbox({
					title: this.$t("hint.Alert"),
					message: this.$t('newcash.confirmToRefuse') + (name?name:dname) + this.$t('newcash.withdrawRequestFrom'),
					showClose: false,
					showCancelButton: true,
					closeOnClickModal:false,
					confirmButtonText: this.$t("button.OK"),
					cancelButtonText: this.$t("button.Cancel"),
					beforeClose: (action, instance, done) => {
					if (action == "confirm") {
						if(state === '0'){
							checkCash(id,0).then(res=>{
								// console.log('驳回按钮返回的信息')
								// console.log(res)
								if(res.code === 1){
									Message({
										message: this.$t('hint.OperationFail'),
										type: 'warning',
										duration: 3 * 1000	
									});	
								}else if(res.code === 0){
									this.getWithdrawCashList(this.searchCashData);
									Message({
										message: this.$t('hint.OperationSuccess'),
										type: 'success',
										duration: 3 * 1000	
									});	
								}
							})
						}
						// else if(state === '1'){
						// 	Message({
						// 		message: this.$t('cash.alreadyPassed'),
						// 		type: 'warning',
						// 		duration: 3 * 1000	
						// 	});
						// }else if(state === '2'){
						// 	Message({
						// 		message: this.$t('cash.notRepeatOperation'),
						// 		type: 'warning',
						// 		duration: 3 * 1000	
						// 	});
						// }else{
						// 	Message({
						// 		message: this.$t('cash.errOperation'),
						// 		type: 'error',
						// 		duration: 3 * 1000	
						// 	});
						// }
					}
					done();
					}
				}).catch(()=>{});
				
			},
		
			//打款
			handerCheckCashPay(id,state,mername){
                this.$msgbox({
					title: this.$t("hint.PaymentConfirmation"),
					message: this.$t('hint.Confirmthewithdrawalrequestof') + mername + this.$t('hint.hasbeenpaid'),
					showClose: false,
					showCancelButton: true,
					closeOnClickModal:false,
					confirmButtonText: this.$t("button.OK"),
					cancelButtonText: this.$t("button.Cancel"),
					beforeClose: (action, instance, done) => {
					if (action == "confirm") {
                        if(state === '1'){
                            withdrawCashPay(id).then(res=>{
                                // console.log('打款按钮返回的信息')
                                // console.log(res)
                                if(res.code === 1){
                                    Message({
                                        message: this.$t('hint.OperationFail'),
                                        type: 'warning',
                                        duration: 3 * 1000	
                                    })
                                }else if(res.code === 0){
                                    this.getWithdrawCashList(this.searchCashData);
                                    Message({
                                        message: this.$t('hint.OperationSuccess'),
                                        type: 'success',
                                        duration: 3 * 1000	
                                    })
                                }else{
                                    Message({
                                        message: res.msg,
                                        type: 'error',
                                        duration: 3 * 1000	
                                    })
                                }
                            })
                        }
					}
					done();
					}
				}).catch(()=>{});
				// else if(state === '0'){
				// 	Message({
				// 	    message: this.$t('cash.audit'),
				// 	    duration: 3 * 1000	
				// 	});
				// }else if(state === '2'){
				// 	Message({
				// 	    message: this.$t('cash.notMakeMoney'),
				// 	    type: 'error',
				// 	    duration: 3 * 1000	
				// 	});
				// }else {
				// 	Message({
				// 	    message: this.$t('cash.alreadyMadeMoney'),
				// 	    duration: 3 * 1000	
				// 	});
				// }
			},
			//pageSize 改变时会触发
		    handleSizeChange(val) {
		        this.searchCashData.pageSize = val;
		        this.getWithdrawCashList(this.searchCashData);
		    },
		    //currentPage 改变时会触发
		    handleCurrentChange(val) {
		        this.searchCashData.page = val;
		        this.getWithdrawCashList(this.searchCashData,'CurrentChange');
		    },
		    formatObj(obj){
				let arr = Object.keys(obj);
				for(let i = 0;i<arr.length;i++){
					if(obj[arr[i]] === ''){
						obj[arr[i]] = null;
					}
				}
			},
		}
	}

</script>

<style scoped>
	.el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>